package org.corey.share.db.service;

import java.util.List;

import org.corey.share.db.dao.BaseDao;
import org.corey.share.db.manager.DefaultDaoFactory;
import org.corey.share.db.manager.EM;

public class DefaultServiceImpl implements DefaultSercive {
	private BaseDao dao = new DefaultDaoFactory().creatBaseDao();

	public boolean add(Object entity) {
		if (entity == null) {
			throw new IllegalArgumentException();
		}
		EM.beginTransaction();
		boolean result = dao.save(entity);
		EM.commitTransaction();
		return result;
	}

	public boolean delete(Long id, Class cls) {
		if (id == null || cls == null) {
			throw new IllegalArgumentException();
		}
		EM.beginTransaction();
		Object entity = this.getEntity(cls, id);
		boolean result = dao.remove(entity);
		EM.commitTransaction();
		return result;
	}

	public <T> List<T> getAll(Class<T> cls) {
		return dao.findAll(0, 0, cls, "id").getPageData();
	}

	public boolean update(Object entity) {
		if (entity == null) {
			throw new IllegalArgumentException();
		}
		EM.beginTransaction();
		boolean result = dao.update(entity);
		EM.commitTransaction();
		return result;
	}

	public <T> T getEntity(Class<T> cls, Long id) {
		if (cls == null || id == null) {
			throw new IllegalArgumentException();
		}
		return (T) dao.load(id, cls);
	}
}
